package ua.races.jsptag;

import org.apache.log4j.Logger;
import ua.races.dao.RacesDaoImpl;
import ua.races.vo.Horse;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;

public class StatisticsTag extends TagSupport {

    private static final Logger log = Logger.getLogger(StatisticsTag.class.getName());

    private Integer history;

    private String align;

    public void setAlign(String align) {
        this.align = align;
    }

    public void setHistory(Integer history) {
        this.history = history;
    }


    public int doStartTag() throws JspException {

        JspWriter w = pageContext.getOut();
        RacesDaoImpl dao;
        dao = (RacesDaoImpl) pageContext.getServletContext().getAttribute("DAO");
        int i, j;

        try {
            Map<Horse, Map<Date, Integer>> results = dao.horseStatistics(history);

            w.println("<h3 align=\"" + align + "\">Statistics of the horses</h3>");
            w.println("<table align=\"" + align + "\" border = \"1\" bgcolor=\"#fff0f5\">");
            w.println("<tr>");
            w.println("<td>Horse name</td>");
            for (i = 1; i <= history; i++) {
                w.println("<td>" + i + "</td>");
            }
            w.println("</tr>");

            for (Horse horse : results.keySet()) {
                w.println("<tr>");
                w.println("<td>" + horse.getHorseName() + "</td>");
                Iterator<Date> iterator = results.get(horse).keySet().iterator();
                while (iterator.hasNext()) {
                    w.println("<td>" + results.get(horse).get(iterator.next()) + "</td>");
                }

                w.println("</tr>");
            }
            w.println("</table><br/>");

        } catch (SQLException e) {
            log.error(e);
        } catch (IOException e) {
            log.error(e);
        }

        return SKIP_BODY;

    }

    public int doEndTag
            () throws JspException {
        return EVAL_PAGE;
    }
}